using System.Collections;
using UnityEngine;

public class EnemyMelee : Enemy
{
    private Coroutine _attackCoroutine;
    private bool _canTrigger;
    private bool _canAttack = true;
    protected override void OnEnable()
    {
        base.OnEnable();
        _canTrigger = true;
    }

    private void OnTriggerStay2D(Collider2D other)
    {
        if (other.CompareTag("Player") == false || _canTrigger == false || _canAttack == false)
            return;
        IDamagable damagable = other.GetComponent<IDamagable>();

        if (damagable == null)
            return;

        Vector2 hurtDir = (other.transform.position - transform.position).normalized;

        damagable.TakeDamage(_enemyStat.GetAttackDamage(), hurtDir);

        _attackCoroutine ??= StartCoroutine(AttackCo());

        StartCoroutine(AttackWaitCo());
    }
    private IEnumerator AttackWaitCo()
    {
        _canAttack = false;
        Debug.Log(_canAttack);
        yield return attackWaitWFX;
        
        _canAttack = true;
    }
    private IEnumerator AttackCo()
    {
        _canChase = false;
        Vector2 dir = transform.position - chaseTarget.position;
        Vector2 originalVelocity = dir * _hurtRepelForce;
        rb.velocity = originalVelocity;
        float timer = 0;
        while (timer < _hurtRepelDuration)
        {
            timer += Time.deltaTime;

            float t = timer / _hurtRepelDuration;

            float easeT = 1 - (1 - t) * (1 - t);

            rb.velocity = Vector2.Lerp(originalVelocity, Vector2.zero, easeT);

            yield return null;
        }

        _canChase = true;
        _attackCoroutine = null;
    } 
    public override void HandlePlayerDead()
    {
        StopAllCoroutines();
        _canTrigger = false;
        
        base.HandlePlayerDead();
    }
}

